<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? '编辑活动' : '新增活动'"
    width="800px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="活动名称" prop="taskName">
            <ElInput
              v-model="form.taskName"
              placeholder="请输入活动名称"
              maxlength="30"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="活动安排" prop="taskArrange">
            <ElInput
              v-model="form.taskArrange"
              placeholder="请输入活动安排"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="活动上架状态" prop="taskUpFlag">
            <ElSelect v-model="form.taskUpFlag" placeholder="请选择上架状态">
              <ElOption label="下架" :value="1" />
              <ElOption label="上架" :value="2" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="举办方" prop="taskHold">
            <ElInput
              v-model="form.taskHold"
              placeholder="请输入举办方"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        
      </ElRow>

      <ElRow :gutter="20">
         <ElCol :span="12">
          <ElFormItem label="联系用户" prop="taskLinkUserName">
            <ElInput
              v-model="form.taskLinkUserName"
              placeholder="请输入联系用户"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="联系电话" prop="taskLinkUserPhone">
            <ElInput
              v-model="form.taskLinkUserPhone"
              placeholder="请输入联系电话"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="联系邮箱" prop="taskLinkUserEmail">
            <ElInput
              v-model="form.taskLinkUserEmail"
              placeholder="请输入联系邮箱"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
       
      </ElRow>
     
      <ElRow :gutter="20">
         <ElCol :span="12">
          <ElFormItem label="最大参与人数" prop="taskMaxPerson">
            <ElInputNumber
              v-model="form.taskMaxPerson"
              :min="1"
              :max="99999"
              placeholder="请输入最大参与人数"
              style="width: 100%;"
            />
          </ElFormItem>
        </ElCol>
      <ElCol :span="12">
          <ElFormItem label="积分" prop="taskScore">
            <ElInputNumber
              v-model="form.taskScore"
              :min="0"
              :max="99999"
              placeholder="请输入积分"
              style="width: 100%;"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="活动开始时间" prop="taskTimeBegin	">
            <el-date-picker
        v-model="form.taskTimeBegin"
        type="date"
        value-format="YYYYMMDDHHmmss"
        placeholder="请选择开始时间"
        style="width: 100%;"
      />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="活动结束时间" prop="taskTimeEnd	">
            
            <el-date-picker
        v-model="form.taskTimeEnd"
        type="date"
        value-format="YYYYMMDDHHmmss"
        placeholder="请选择结束时间"
        style="width: 100%;"
      />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
      </ElRow>
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="位置信息" prop="taskAddress">
            <div class="flex items-center w-full">
              <div class="flex-1">
                <el-input v-model="form.taskAddress" placeholder="请输入位置信息" />
              </div>
              <el-button class="ml-2" @click="openMapSelection">
                <el-icon>
                  <Location />
                </el-icon>
              </el-button>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="参与要求" prop="taskRequire">
            <ElInput
              v-model="form.taskRequire"
              placeholder="参与要求"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="活动介绍" prop="taskInfo">
            <ElInput
              v-model="form.taskInfo"
              placeholder="请输入活动介绍"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="活动图片" prop="taskPhoto">
            <proUploadImg
              v-model:fileList="taskPhoto"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
              tip="图片大小不超过20MB"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="活动附件" prop="taskFile">
            <ProUploadFile
              v-model:fileList="taskFile"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="handleSubmit"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>

  <MapSelection
    ref="mapSelectionRef"
    :title="mapSelectionDialog.title"
    :visible="mapSelectionDialog.visible"
    @getLocationSuccess="handleLocationSuccess"
    @mapClose="mapSelectionDialog.visible = false"
  />
</template>

<script setup lang="ts">
  import { ref, reactive,computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { taskInfoSaveDataUsingPost,taskInfoUpdateDataUsingPost, GeoAreaVo } from '@/api'
  import MapSelection from '@/components/core/map/index.vue'


  // 类型定义
  interface Props {
    modelValue: boolean
    actData?: GeoAreaVo | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    actData: undefined
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()

  const loading = ref(false)

  const taskPhoto = ref([])

  const taskFile = ref([])

  const form = reactive({
  taskUpFlag: 1,
  taskArrange: "",
  taskPhoto: '',
  taskFile: "",
  taskTimeBegin: "",
  taskLinkUserEmail: "",
  taskHold: "",
  taskMaxPerson: 1,
  taskAddress: "",
  taskLongitude: "",
  taskLatitude: "",
  taskLinkUserPhone: "",
  taskRequire: "",
  taskName: "",
  taskScore: 0,
  taskInfo: "",
  taskLinkUserName: "",
  taskTimeEnd: ""
  })

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const isEdit = computed(() => !!props.actData?.id)

  // 表单验证规则
  const rules: FormRules = {
    taskName: [
      { required: true, message: '请输入活动名称', trigger: 'blur' },
      { max: 30, message: '活动名称不能超过30个字符', trigger: 'blur' }
    ],
    taskUpFlag: [
      { required: true, message: '请选择上架状态', trigger: 'change' },
    ],
    taskHold: [
      { required: true, message: '请输入举办方', trigger: 'blur' },
      { max: 30, message: '举办方不能超过30个字符', trigger: 'blur' }
    ],
    taskLinkUserName: [
      { required: true, message: '请输入联系人', trigger: 'blur' },
      { max: 10, message: '联系人不能超过10个字符', trigger: 'blur' }
    ],
    taskLinkUserPhone: [
      { required: true, message: '请输入联系人电话', trigger: 'blur' },
      { max: 11, message: '联系人电话不能超过11个字符', trigger: 'blur' }
    ],
    taskRequire: [
      { required: true, message: '请输入参与要求', trigger: 'blur' },
      { max: 500, message: '参与要求不能超过500个字符', trigger: 'blur' }
    ],
    taskMaxPerson: [
      { required: true, message: '请输入最大参与人数', trigger: 'blur' },
    ],
    taskScore: [
      { required: true, message: '请输入积分', trigger: 'blur' },
    ],
    taskTimeBegin: [
      { required: true, message: '请选择活动开始时间', trigger: ['blur','change'] },
    ],
    taskTimeEnd: [
     { required: true, message: '请选择活动结束时间', trigger: ['blur','change'] },
    ],
    
    taskInfo: [
      { required: true, message: '请输入活动介绍', trigger: 'blur' },
      { max: 500, message: '小区名称不能超过500个字符', trigger: 'blur' }
    ],
    taskAddress: [
      { required: true, message: '请输入位置信息', trigger: ['blur', 'change'] },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入位置信息'))
            return
          }
          // 校验经度和纬度
          if (!form.taskLongitude || !form.taskLatitude) {
            callback(new Error('请选择位置信息（经度和纬度）'))
            return
          }
          callback()
        },
        trigger: ['blur', 'change']
      }
    ],
    
    taskFile: [
      {
        required: true,
        message: '请上传小区图片',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (taskFile.value.length === 0) {
            callback(new Error('请上传小区图片'))
            return
          }
          callback()
        }
      }
    ]
  }

  const mapSelectionRef = ref()
  const mapSelectionDialog = ref({
    visible: false,
    title: '选择位置'
  })

  // 打开地图选择
  const openMapSelection = () => {
    //初始化地图的经纬度，还有地址
    mapSelectionRef.value.initMapLatLng({
      longitude: form.taskLongitude || '114.3203',
      latitude: form.taskLatitude || '30.3505',
      address: form.taskAddress
    })
    mapSelectionDialog.value.visible = true
  }

  // 获取位置成功
  const handleLocationSuccess = (location: any) => {
    form.taskLongitude = location.longitude
    form.taskLatitude = location.latitude
    form.taskAddress = location.address
    mapSelectionDialog.value.visible = false
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true
      if(isEdit.value){
       const res = await taskInfoUpdateDataUsingPost({
        body: {
          ...form,
          taskPhoto: JSON.stringify(taskPhoto.value),
          taskFile: JSON.stringify(taskFile.value),
        }
      })
      if(res.code == 0){
        formRef.value?.resetFields()
      }
      }else {
     const res = await taskInfoSaveDataUsingPost({
        body: {
          ...form,
          taskPhoto: JSON.stringify(taskPhoto.value),
          taskFile: JSON.stringify(taskFile.value),
        }
      })
      if(res.code == 0){
        formRef.value?.resetFields()
      }
      }
      
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('success')
    } finally {
      loading.value = false
    }
  }

  const handleOpen = () => {
    if (isEdit.value) {
      taskFile.value = JSON.parse(props.actData?.taskFile || '[]')
      taskPhoto.value = JSON.parse(props.actData?.taskPhoto || '[]')
      nextTick(() => {
        if(props.actData) {
          Object.assign(form,props.actData)
        }
      })
    } else {
      formRef.value?.resetFields()
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    taskFile.value = []
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.service-item) {
    .el-form-item__content {
      .el-form-item__error {
        margin-top: -12px;
        margin-left: 46px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
